home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / pyshared / jockey / backend.py next >
Encoding:
Python Source  |  2009-04-07  |  27.4 KB  |  752 lines

  1. # -*- coding: UTF-8 -*-
  2.  
  3. # (c) 2008 Canonical Ltd.
  4. #
  5. # This program is free software; you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation; either version 2 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License along
  16. # with this program; if not, write to the Free Software Foundation, Inc.,
  17. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  18.  
  19. '''Backend manager.
  20.  
  21. This encapsulates all services of the backend and manages all handlers.
  22. '''
  23.  
  24. import logging, os, os.path, signal, threading, sys
  25.  
  26. import gobject
  27. import dbus
  28. import dbus.service
  29. import dbus.mainloop.glib
  30.  
  31. from oslib import OSLib
  32. import detection, xorg_driver
  33.  
  34. DBUS_BUS_NAME = 'com.ubuntu.DeviceDriver'
  35.  
  36. #--------------------------------------------------------------------#
  37.  
  38. class UnknownHandlerException(dbus.DBusException):
  39.     _dbus_error_name = 'com.ubuntu.DeviceDriver.UnknownHandlerException'
  40.  
  41. class InvalidModeException(dbus.DBusException):
  42.     _dbus_error_name = 'com.ubuntu.DeviceDriver.InvalidModeException'
  43.  
  44. class InvalidDriverDBException(dbus.DBusException):
  45.     _dbus_error_name = 'com.ubuntu.DeviceDriver.InvalidDriverDBException'
  46.  
  47. class PermissionDeniedByPolicy(dbus.DBusException):
  48.     _dbus_error_name = 'com.ubuntu.DeviceDriver.PermissionDeniedByPolicy'
  49.  
  50. class BackendCrashError(SystemError):
  51.     pass
  52.  
  53. #--------------------------------------------------------------------#
  54.  
  55. def dbus_sync_call_signal_wrapper(dbus_iface, fn, handler_map, *args, **kwargs):
  56.     '''Run a D-BUS method call while receiving signals.
  57.  
  58.     This function is an Ugly Hack‚Ñ¢, since a normal synchronous dbus_iface.fn()
  59.     call does not cause signals to be received until the method returns. Thus
  60.     it calls fn asynchronously and sets up a temporary main loop to receive
  61.     signals and call their handlers; these are assigned in handler_map (signal
  62.     name ‚Üí signal handler).
  63.     '''
  64.     if not hasattr(dbus_iface, 'connect_to_signal'):
  65.         # not a D-BUS object
  66.         return getattr(dbus_iface, fn)(*args, **kwargs)
  67.  
  68.     def _h_reply(result):
  69.         global _h_reply_result
  70.         _h_reply_result = result
  71.         loop.quit()
  72.  
  73.     def _h_error(exception):
  74.         global _h_exception_exc
  75.         _h_exception_exc = exception
  76.         loop.quit()
  77.  
  78.     loop = gobject.MainLoop()
  79.     global _h_reply_result, _h_exception_exc
  80.     _h_reply_result = None
  81.     _h_exception_exc = None
  82.     kwargs['reply_handler'] = _h_reply
  83.     kwargs['error_handler'] = _h_error
  84.     kwargs['timeout'] = 86400
  85.     for signame, sighandler in handler_map.iteritems():
  86.         dbus_iface.connect_to_signal(signame, sighandler)
  87.     dbus_iface.get_dbus_method(fn)(*args, **kwargs)
  88.     loop.run()
  89.     if _h_exception_exc:
  90.         raise _h_exception_exc
  91.     return _h_reply_result
  92.  
  93. #--------------------------------------------------------------------#
  94.  
  95. def polkit_auth_wrapper(fn, *args, **kwargs):
  96.     '''Function call wrapper for PolicyKit authentication.
  97.  
  98.     Call fn(*args, **kwargs). If it fails with a PermissionDeniedByPolicy
  99.     and the caller can authenticate to get the missing privilege, the PolicyKit
  100.     authentication agent is called, and the function call is attempted again.
  101.  
  102.     This function also translates DBusExceptions into the Exceptions defined
  103.     above.
  104.     '''
  105.     try:
  106.         try:
  107.             return fn(*args, **kwargs)
  108.         except dbus.DBusException, e:
  109.             if e._dbus_error_name == PermissionDeniedByPolicy._dbus_error_name:
  110.                 # last words in message are privilege and auth result
  111.                 (priv, auth_result) = str(e).split()[-2:]
  112.                 if auth_result.startswith('auth_'):
  113.                     pk_auth = dbus.Interface(dbus.SessionBus().get_object(
  114.                         'org.freedesktop.PolicyKit.AuthenticationAgent', '/', False),
  115.                         'org.freedesktop.PolicyKit.AuthenticationAgent')
  116.                     # TODO: provide xid
  117.                     res = pk_auth.ObtainAuthorization(priv, dbus.UInt32(0),
  118.                         dbus.UInt32(os.getpid()), timeout=300)
  119.                     if res:
  120.                         return fn(*args, **kwargs)
  121.                 raise PermissionDeniedByPolicy(priv + ' ' + auth_result)
  122.             raise
  123.     except dbus.DBusException, e:
  124.         if e._dbus_error_name == InvalidModeException._dbus_error_name:
  125.             raise InvalidModeException(str(e))
  126.         elif e._dbus_error_name == UnknownHandlerException._dbus_error_name:
  127.             raise UnknownHandlerException(str(e))
  128.         elif e._dbus_error_name == 'org.freedesktop.DBus.Python.SystemError':
  129.             raise SystemError(str(e))
  130.         elif e._dbus_error_name == 'org.freedesktop.DBus.Error.NoReply':
  131.             raise BackendCrashError
  132.         else:
  133.             raise
  134.  
  135. #--------------------------------------------------------------------#
  136.  
  137. class Backend(dbus.service.Object):
  138.     '''Backend manager.
  139.  
  140.     This encapsulates all services of the backend and manages all handlers. It
  141.     is implemented as a dbus.service.Object, so that it can be called through
  142.     D-BUS as well (on the /DeviceDriver object path).
  143.     '''
  144.     DBUS_INTERFACE_NAME = 'com.ubuntu.DeviceDriver'
  145.  
  146.     def __init__(self, handler_dir=None, detect=True):
  147.         '''Initialize backend (no hardware/driver detection).
  148.  
  149.         In order to be fast and not block client side applications for very
  150.         long, detect can be set to False; in that case this constructor does
  151.         not detect hardware and drivers, and client-side applications must call
  152.         detect() at program start.
  153.         '''
  154.         self.handler_dir = handler_dir
  155.         self.handler_pool = {}
  156.         self.hardware = None
  157.  
  158.         # cached D-BUS interfaces for _check_polkit_privilege()
  159.         self.dbus_info = None
  160.         self.polkit = None
  161.  
  162.         self.enforce_polkit = True
  163.         self._package_operation_in_progress = False
  164.  
  165.         if detect:
  166.             self.detect()
  167.  
  168.     #
  169.     # Client API (through D-BUS)
  170.     #
  171.  
  172.     @dbus.service.method(DBUS_INTERFACE_NAME,
  173.         in_signature='', out_signature='', sender_keyword='sender',
  174.         connection_keyword='conn')
  175.     def detect(self, sender=None, conn=None):
  176.         '''Detect available hardware and handlers.
  177.  
  178.         This method can take pretty long, so it should be called asynchronously
  179.         with a large (or indefinite) timeout, and client UIs should display a
  180.         bouncing progress bar (if appropriate). If the backend is already
  181.         initialized, this returns immediately.
  182.  
  183.         This must be called once at client-side program start.
  184.         '''
  185.         self._reset_timeout()
  186.         self._check_polkit_privilege(sender, conn, 'com.ubuntu.devicedriver.info')
  187.  
  188.         if not self.hardware:
  189.             self.hardware = detection.get_hardware()
  190.             self.driver_dbs = [detection.LocalKernelModulesDriverDB(),
  191.                 detection.OpenPrintingDriverDB()]
  192.             self._detect_handlers()
  193.  
  194.     @dbus.service.method(DBUS_INTERFACE_NAME,
  195.         in_signature='s', out_signature='as', sender_keyword='sender',
  196.         connection_keyword='conn')
  197.     def available(self, mode='any', sender=None, conn=None):
  198.         '''List available driver IDs.
  199.         
  200.         Mode can be "any" (default) to return all available drivers, or
  201.         "free"/"nonfree" to select by license.
  202.         '''
  203.         self._reset_timeout()
  204.         self._check_polkit_privilege(sender, conn, 'com.ubuntu.devicedriver.info')
  205.  
  206.         if mode == 'any':
  207.             return self.handlers.keys()
  208.  
  209.         if mode not in ('free', 'nonfree'):
  210.             raise InvalidModeException(
  211.                 'invalid mode %s: must be "free", "nonfree", or "any"' % mode)
  212.  
  213.         recommended = []
  214.         nonrecommended = []
  215.         for (h_id, h) in self.handlers.iteritems():
  216.             if h.free() == (mode == 'free'):
  217.                 if h.recommended():
  218.                     recommended.append(h_id)
  219.                 else:
  220.                     nonrecommended.append(h_id)
  221.         return recommended + nonrecommended
  222.  
  223.     @dbus.service.method(DBUS_INTERFACE_NAME,
  224.         in_signature='', out_signature='as', sender_keyword='sender',
  225.         connection_keyword='conn')
  226.     def get_hardware(self, sender=None, conn=None):
  227.         '''List available hardware IDs.'''
  228.  
  229.         self._reset_timeout()
  230.         self._check_polkit_privilege(sender, conn, 'com.ubuntu.devicedriver.info')
  231.         return [hwid.type + ':' + hwid.id for hwid in self.hardware]
  232.  
  233.     @dbus.service.method(DBUS_INTERFACE_NAME,
  234.         in_signature='s', out_signature='a{ss}', sender_keyword='sender',
  235.         connection_keyword='conn')
  236.     def handler_info(self, handler_id, sender=None, conn=None):
  237.         '''Return details about a particular handler.
  238.  
  239.         The information is returned in a property_name ‚Üí property_value
  240.         dictionary. Boolean values are encoded as 'True' and 'False' strings.
  241.         If a particular attribute is not set, it will not appear in the
  242.         dictionary.
  243.         '''
  244.         self._reset_timeout()
  245.         self._check_polkit_privilege(sender, conn, 'com.ubuntu.devicedriver.info')
  246.  
  247.         try:
  248.             h = self.handlers[handler_id]
  249.         except KeyError:
  250.             raise UnknownHandlerException('Unknown handler: %s' % handler_id)
  251.  
  252.         info = {
  253.             'id': h.id(),
  254.             'name': h.name(),
  255.             'free': str(h.free()),
  256.             'enabled': str(h.enabled()),
  257.             'used': str(h.used()),
  258.             'changed': str(h.changed()),
  259.             'recommended': str(h.recommended()),
  260.             'announce': str(h.announce),
  261.         }
  262.         for f in ['description', 'rationale', 'can_change']:
  263.             v = getattr(h, f)()
  264.             if v:
  265.                 info[f] = v
  266.         for f in ['package', 'repository', 'driver_vendor', 'version',
  267.             'license']:
  268.             v = getattr(h, f)
  269.             if v:
  270.                 info[f] = v
  271.  
  272.         return info
  273.  
  274.     @dbus.service.method(DBUS_INTERFACE_NAME,
  275.         in_signature='s', out_signature='as', sender_keyword='sender',
  276.         connection_keyword='conn')
  277.     def handler_files(self, handler_id, sender=None, conn=None):
  278.         '''Return list of files installed by a handler.'''
  279.  
  280.         try:
  281.             h = self.handlers[handler_id]
  282.         except KeyError:
  283.             raise UnknownHandlerException('Unknown handler: %s' % handler_id)
  284.  
  285.         if not h.package or not h.enabled():
  286.             return []
  287.  
  288.         try:
  289.             return OSLib.inst.package_files(h.package)
  290.         except ValueError:
  291.             return []
  292.  
  293.     @dbus.service.method(DBUS_INTERFACE_NAME,
  294.         in_signature='sb', out_signature='b', sender_keyword='sender',
  295.         connection_keyword='conn')
  296.     def set_enabled(self, handler_id, enable, sender=None, conn=None):
  297.         '''Enable or disable a driver.
  298.  
  299.         This enables (enable=True) or disables (enable=False) the given Driver
  300.         ID. Return True if the handler could be activated immediately, or False
  301.         if the system needs a reboot for the changes to become effective.
  302.         '''
  303.         self._reset_timeout()
  304.         self._check_polkit_privilege(sender, conn, 'com.ubuntu.devicedriver.install')
  305.  
  306.         try:
  307.             h = self.handlers[handler_id]
  308.         except KeyError:
  309.             raise UnknownHandlerException('Unknown handler: %s' % handler_id)
  310.  
  311.         if enable:
  312.             f = h.enable
  313.         else:
  314.             f = h.disable
  315.  
  316.         if not conn:
  317.             # not called through D-BUS, thus don't send progress signals
  318.             return f()
  319.  
  320.         if h.package:
  321.             # start progress information early; for package operations we will
  322.             # always have a progress bar, avoid delays from the package manager
  323.             # with progress reporting
  324.             if enable:
  325.                 self.install_progress('download', -1, -1)
  326.             else:
  327.                 self.remove_progress(-1, -1)
  328.  
  329.         def _f_result_wrapper():
  330.             try:
  331.                 self._f_result = f()
  332.             except:
  333.                 self._f_exception = sys.exc_info()
  334.  
  335.         # Call enable/disable in a separate thread, in case it does long
  336.         # actions and thus we need to signal progress
  337.         self._f_exception = None
  338.         t_f = threading.Thread(None, _f_result_wrapper,
  339.             'thread_enable_disable', [], {})
  340.         t_f.start()
  341.         while True:
  342.             t_f.join(0.2)
  343.             if not t_f.isAlive():
  344.                 break
  345.             # {install,remove}_package() already report percentage process,
  346.             # don't interfere with that
  347.             if not self._package_operation_in_progress:
  348.                 if enable:
  349.                     self.install_progress('install', -1, -1)
  350.                 else:
  351.                     self.remove_progress(-1, -1)
  352.         if self._f_exception:
  353.             raise self._f_exception[0], self._f_exception[1], self._f_exception[2]
  354.         return self._f_result
  355.  
  356.     @dbus.service.method(DBUS_INTERFACE_NAME,
  357.         in_signature='s', out_signature='(asas)', sender_keyword='sender',
  358.         connection_keyword='conn')
  359.     def new_used_available(self, mode='any', sender=None, conn=None):
  360.         '''Check for newly used or available drivers since last call.
  361.         
  362.         Return (new_used, new_avail) with lists of new drivers which are in
  363.         use, and new drivers which got available but are disabled.
  364.         Mode can be "any" (default) to return all available drivers, or
  365.         "free"/"nonfree" to select by license.
  366.         '''
  367.         self._reset_timeout()
  368.         self._check_polkit_privilege(sender, conn, 'com.ubuntu.devicedriver.check')
  369.  
  370.         if mode not in ('any', 'free', 'nonfree'):
  371.             raise InvalidModeException(
  372.                 'invalid mode %s: must be "free", "nonfree", or "any"' % mode)
  373.  
  374.         # read previously seen/used handlers
  375.         seen = set()
  376.         used = set()
  377.  
  378.         if os.path.exists(OSLib.inst.check_cache):
  379.             f = open(OSLib.inst.check_cache)
  380.             for line in f:
  381.                 try:
  382.                     (flag, h) = line.split(None, 1)
  383.                     h = unicode(h, 'UTF-8')
  384.                 except ValueError:
  385.                     logging.error('invalid line in %s: %s',
  386.                         OSLib.inst.check_cache, line)
  387.                 if flag == 'seen':
  388.                     seen.add(h.strip())
  389.                 elif flag == 'used':
  390.                     used.add(h.strip())
  391.                 else:
  392.                     logging.error('invalid flag in %s: %s',
  393.                         OSLib.inst.check_cache, line)
  394.             f.close()
  395.  
  396.         # check for newly used/available handlers
  397.         new_avail = []
  398.         new_used = []
  399.         for h_id, h in self.handlers.iteritems():
  400.             if (mode == 'free' and not h.free()) or \
  401.                (mode == 'nonfree' and h.free()):
  402.                continue
  403.             if h_id not in seen:
  404.                 new_avail.append(h_id)
  405.                 logging.debug('handler %s previously unseen', h_id)
  406.             if h_id not in used and h.used():
  407.                 new_used.append(h_id)
  408.                 logging.debug('handler %s previously unused', h_id)
  409.  
  410.         # write back cache
  411.         logging.debug('writing back check cache %s', 
  412.             OSLib.inst.check_cache)
  413.         seen.update(new_avail)
  414.         used.update(new_used)
  415.         f = open(OSLib.inst.check_cache, 'w')
  416.         for s in seen:
  417.             print >> f, 'seen', s
  418.         for u in used:
  419.             print >> f, 'used', u
  420.         f.close()
  421.  
  422.         # throw out newly available handlers which are already enabled, no need
  423.         # to bother people about them
  424.         for h_id in new_avail + []: # create a copy for iteration
  425.             try:
  426.                 if self.handlers[h_id].enabled():
  427.                     logging.debug('%s is already enabled or not available, not announcing', h_id)
  428.                     new_avail.remove(h_id)
  429.             except ValueError:
  430.                 # thrown if package does not exist; might be a race condition
  431.                 # between jockey --check and a cron job fetching new package
  432.                 # indexes at session start, see LP #200089
  433.                 continue
  434.  
  435.         return (new_used, new_avail)
  436.  
  437.     @dbus.service.method(DBUS_INTERFACE_NAME,
  438.         in_signature='', out_signature='s', sender_keyword='sender',
  439.         connection_keyword='conn')
  440.     def check_composite(self, sender=None, conn=None):
  441.         '''Check for a composite-enabling X.org driver.
  442.  
  443.         If one is available and not enabled, return its ID, otherwise return
  444.         an empty string.
  445.         '''
  446.         self._reset_timeout()
  447.         self._check_polkit_privilege(sender, conn, 'com.ubuntu.devicedriver.info')
  448.  
  449.         for h_id, h in self.handlers.iteritems():
  450.             if isinstance(h, xorg_driver.XorgDriverHandler) and \
  451.                 h.enables_composite():
  452.                 if h.enabled():
  453.                     logging.debug('Driver "%s" is already enabled and supports the composite extension.' % h.name())
  454.                     return ''
  455.                 else:
  456.                     return h_id
  457.         return ''
  458.  
  459.     @dbus.service.method(DBUS_INTERFACE_NAME,
  460.         in_signature='sas', out_signature='', sender_keyword='sender',
  461.         connection_keyword='conn')
  462.     def add_driverdb(self, db_class, db_args, sender=None, conn=None):
  463.         '''Add driver DB.
  464.  
  465.         db_class is a DriverDB class name; db_args are its constructor
  466.         arguments. If there is an error instantiating the driver DB, an
  467.         InvalidDriverDBException is thrown.
  468.         '''
  469.         try:
  470.             cls = getattr(detection, db_class)
  471.         except AttributeError, e:
  472.             raise InvalidDriverDBException(str(e))
  473.  
  474.         try:
  475.             inst = cls(*db_args)
  476.         except Exception, e:
  477.             raise InvalidDriverDBException(str(e))
  478.  
  479.         logging.debug('add_driverdb: Adding %s', str(inst))
  480.  
  481.         self.driver_dbs.append(inst)
  482.  
  483.         # do not call _detect_handlers(), it re-detects everything
  484.         for h in detection.get_db_handlers(self, inst, self.hardware):
  485.             self.handlers[h.id()] = h
  486.  
  487.     @dbus.service.method(DBUS_INTERFACE_NAME,
  488.         in_signature='', out_signature='', sender_keyword='sender',
  489.         connection_keyword='conn')
  490.     def update_driverdb(self, sender=None, conn=None):
  491.         '''Query driver DBs for updates.'''
  492.  
  493.         self._reset_timeout()
  494.         self._check_polkit_privilege(sender, conn, 'com.ubuntu.devicedriver.update')
  495.  
  496.         for db in self.driver_dbs:
  497.             logging.debug('update_driverdb: updating %s', db.__class__)
  498.             db.update(self.hardware)
  499.  
  500.         self._detect_handlers()
  501.  
  502.     @dbus.service.method(DBUS_INTERFACE_NAME,
  503.         in_signature='s', out_signature='as', sender_keyword='sender',
  504.         connection_keyword='conn')
  505.     def search_driver(self, hwid, sender=None, conn=None):
  506.         '''Search drivers matching a HardwareID.
  507.  
  508.         This also finds drivers for hardware which is not present locally and
  509.         thus checks all the driver DBs again.
  510.  
  511.         Mode can be "any" (default) to return all available drivers, or
  512.         "free"/"nonfree" to select by license.
  513.         '''
  514.         # TODO: support freeness mode
  515.         self._reset_timeout()
  516.         self._check_polkit_privilege(sender, conn, 'com.ubuntu.devicedriver.info')
  517.  
  518.         (t, i) = hwid.split(':', 1)
  519.         hardware_id = detection.HardwareID(t, i)
  520.  
  521.         recommended = []
  522.         nonrecommended = []
  523.         for db in self.driver_dbs:
  524.             db.update([hardware_id])
  525.         handlers = detection.get_handlers(self, self.driver_dbs,
  526.             hardware=[hardware_id], hardware_only=True)
  527.         for h in handlers:
  528.             id = h.id()
  529.             if id not in self.handlers:
  530.                 self.handlers[id] = h
  531.             if h.recommended():
  532.                 recommended.append(id)
  533.             else:
  534.                 nonrecommended.append(id)
  535.  
  536.         return recommended + nonrecommended
  537.  
  538.     @dbus.service.signal(DBUS_INTERFACE_NAME)
  539.     def install_progress(self, phase, curr, total):
  540.         '''Report package installation progress.
  541.  
  542.         'phase' is 'download' or 'install'. current and/or total might be -1 if
  543.         time cannot be determined.
  544.         '''
  545.         return False # TODO: cancel not implemented
  546.  
  547.     @dbus.service.signal(DBUS_INTERFACE_NAME)
  548.     def remove_progress(self, curr, total):
  549.         '''Report package removal progress.
  550.  
  551.         current and/or total might be -1 if time cannot be determined.
  552.         '''
  553.         return False
  554.  
  555.     #
  556.     # Internal API for calling from Handlers (not exported through D-BUS)
  557.     #
  558.  
  559.     def install_package(self, package):
  560.         '''Install software package.'''
  561.  
  562.         if OSLib.inst.package_installed(package):
  563.             return
  564.  
  565.         # only pass D-BUS signal callback if we are called as a D-BUS backend
  566.         self._package_operation_in_progress = True
  567.         OSLib.inst.install_package(package, 
  568.             hasattr(self, '_locations') and self.install_progress or None)
  569.         if OSLib.inst.package_installed(package):
  570.             self._update_installed_packages([package], [])
  571.         self._package_operation_in_progress = False
  572.  
  573.     def remove_package(self, package):
  574.         '''Remove software package.'''
  575.  
  576.         if not OSLib.inst.package_installed(package):
  577.             return
  578.  
  579.         # only pass D-BUS signal callback if we are called as a D-BUS backend
  580.         self._package_operation_in_progress = True
  581.         OSLib.inst.remove_package(package,
  582.             hasattr(self, '_locations') and self.remove_progress or None)
  583.         if not OSLib.inst.package_installed(package):
  584.             self._update_installed_packages([], [package])
  585.         self._package_operation_in_progress = False
  586.  
  587.     #
  588.     # D-BUS control API
  589.     #
  590.  
  591.     def run_dbus_service(self, timeout=None, send_usr1=False):
  592.         '''Run D-BUS server.
  593.  
  594.         If no timeout is given, the server will run forever, otherwise it will
  595.         return after the specified number of seconds.
  596.  
  597.         If send_usr1 is True, this will send a SIGUSR1 to the parent process
  598.         once the server is ready to take requests.
  599.         '''
  600.         dbus.service.Object.__init__(self, self.bus, '/DeviceDriver')
  601.         main_loop = gobject.MainLoop()
  602.         self._timeout = False
  603.         if timeout:
  604.             def _t():
  605.                 main_loop.quit()
  606.                 return True
  607.             gobject.timeout_add(timeout * 1000, _t)
  608.  
  609.         # send parent process a signal that we are ready now
  610.         if send_usr1:
  611.             os.kill(os.getppid(), signal.SIGUSR1)
  612.  
  613.         # run until we time out
  614.         while not self._timeout:
  615.             if timeout:
  616.                 self._timeout = True
  617.             main_loop.run()
  618.  
  619.     @classmethod
  620.     def create_dbus_server(klass, session_bus=False, handler_dir=None):
  621.         '''Return a D-BUS server backend instance.
  622.  
  623.         Normally this connects to the system bus. Set session_bus to True to
  624.         connect to the session bus (for testing). 
  625.         
  626.         The created backend does not yet have hardware and drivers detected,
  627.         thus clients need to call detect().
  628.         '''
  629.         import dbus.mainloop.glib
  630.  
  631.         backend = Backend(handler_dir, detect=False)
  632.         dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
  633.         if session_bus:
  634.             backend.bus = dbus.SessionBus()
  635.             backend.enforce_polkit = False
  636.         else:
  637.             backend.bus = dbus.SystemBus()
  638.         backend.dbus_name = dbus.service.BusName(DBUS_BUS_NAME, backend.bus)
  639.         return backend
  640.  
  641.     @classmethod
  642.     def create_dbus_client(klass, session_bus=False):
  643.         '''Return a client-side D-BUS interface for Backend.
  644.  
  645.         Normally this connects to the system bus. Set session_bus to True to
  646.         connect to the session bus (for testing).
  647.         '''
  648.         dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
  649.         if session_bus:
  650.             bus = dbus.SessionBus()
  651.         else:
  652.             bus = dbus.SystemBus()
  653.         obj = bus.get_object(DBUS_BUS_NAME, '/DeviceDriver')
  654.         return dbus.Interface(obj, Backend.DBUS_INTERFACE_NAME)
  655.  
  656.     #
  657.     # Internal methods
  658.     #
  659.  
  660.     def _update_installed_packages(self, add, remove):
  661.         '''Update backup_dir/installed_packages list of driver packages.
  662.         
  663.         This keeps a log of all packages that jockey installed for supporting
  664.         drivers, so that distribution installers on live CDs can push them into
  665.         the installed system as well.
  666.  
  667.         add and remove are lists which package names to add/remove from it.
  668.         '''
  669.         # get current list
  670.         current = set()
  671.         path = os.path.join(OSLib.inst.backup_dir, 'installed_packages')
  672.         if os.path.exists(path):
  673.             for line in open(path):
  674.                 line = line.strip()
  675.                 if line:
  676.                     current.add(line)
  677.     
  678.         current = current.union(add).difference(remove)
  679.         
  680.         if current:
  681.             # write it back
  682.             f = open(path, 'w')
  683.             for p in current:
  684.                 print >> f, p
  685.             f.close()
  686.         else:
  687.             # delete it if it is empty
  688.             if os.path.exists(path):
  689.                 os.unlink(path)
  690.  
  691.     def _detect_handlers(self):
  692.         '''Detect available handlers and their state.
  693.         
  694.         This initializes self.handlers as id ‚Üí Handler map.'''
  695.  
  696.         self.handlers = {}
  697.         for h in detection.get_handlers(self,
  698.                 self.driver_dbs,
  699.                 handler_dir=self.handler_dir,
  700.                 hardware=self.hardware):
  701.             self.handlers[h.id()] = h
  702.  
  703.     def _reset_timeout(self):
  704.         '''Reset the D-BUS server timeout.'''
  705.  
  706.         self._timeout = False
  707.  
  708.     def _check_polkit_privilege(self, sender, conn, privilege):
  709.         '''Verify that sender has a given PolicyKit privilege.
  710.  
  711.         sender is the sender's (private) D-BUS name, such as ":1:42"
  712.         (sender_keyword in @dbus.service.methods). conn is
  713.         the dbus.Connection object (connection_keyword in
  714.         @dbus.service.methods). privilege is the PolicyKit privilege string.
  715.  
  716.         This method returns if the caller is privileged, and otherwise throws a
  717.         PermissionDeniedByPolicy exception.
  718.         '''
  719.         if sender is None and conn is None:
  720.             # called locally, not through D-BUS
  721.             return
  722.         if not self.enforce_polkit:
  723.             # that happens for testing purposes when running on the session
  724.             # bus, and it does not make sense to restrict operations here
  725.             return
  726.  
  727.         # get peer PID
  728.         if self.dbus_info is None:
  729.             self.dbus_info = dbus.Interface(conn.get_object('org.freedesktop.DBus',
  730.                 '/org/freedesktop/DBus/Bus', False), 'org.freedesktop.DBus')
  731.         pid = self.dbus_info.GetConnectionUnixProcessID(sender)
  732.         
  733.         # query PolicyKit
  734.         if self.polkit is None:
  735.             self.polkit = dbus.Interface(dbus.SystemBus().get_object(
  736.                 'org.freedesktop.PolicyKit', '/', False),
  737.                 'org.freedesktop.PolicyKit')
  738.         try:
  739.             res = self.polkit.IsProcessAuthorized(privilege, pid, True)
  740.         except dbus.DBusException, e:
  741.             if e._dbus_error_name == 'org.freedesktop.DBus.Error.ServiceUnknown':
  742.                 # polkitd timed out, connect again
  743.                 self.polkit = None
  744.                 return self._check_polkit_privilege(sender, conn, privilege)
  745.             else:
  746.                 raise
  747.  
  748.         if res != 'yes':
  749.             logging.debug('_check_polkit_privilege: sender %s on connection %s pid %i requested %s: %s' % (
  750.                 sender, conn, pid, privilege, res))
  751.             raise PermissionDeniedByPolicy(privilege + ' ' + res)
  752.